package fr.istic.linkedcv.client.presentation.views.impl;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import fr.istic.linkedcv.client.presentation.impl.UiImpl;
import fr.istic.linkedcv.client.presentation.views.View;
import fr.istic.linkedcv.client.services.PersonneService;
import fr.istic.linkedcv.client.services.PersonneServiceAsync;


public class InscriptionForm extends View{
	TextBox login = new TextBox();
	PasswordTextBox password = new PasswordTextBox();
	Label idLabel = new Label("Identifiant : ");
	Label pwdLabel = new Label("Password : ");
	Button submitBtn = new Button("S'inscrire");
	private final PersonneServiceAsync personneService = GWT.create(PersonneService.class);
	private Grid grid = new Grid(3,2);
	public InscriptionForm(UiImpl ui){
		super(ui);
	}

	public void build() {
		submitHandler();
		grid.setWidget(0, 0, idLabel);		
		grid.setWidget(0, 1, login);
		grid.setWidget(1, 0, pwdLabel);
		grid.setWidget(1, 1, password);
		grid.setWidget(2, 0, submitBtn);
		grid.setHeight("90px");
		grid.setWidth("300px");
		grid.addStyleName("inscription_form");
		
	}
	
	public void submitHandler(){
		submitBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				 if (login.getValue().isEmpty()) {
	                    Window.alert("Le champ identifiant doit être saisi.");
				 }else  if (password.getValue().isEmpty()) {
	                    Window.alert("Le champ password doit être saisi.");
				 }else
					 addPersonne();
				
			}
		});
	}

	public void addPersonne() {
		Map<String, String> personneMap = new HashMap<String, String>();
		personneMap.put("identifiant", login.getValue());
		personneMap.put("password", password.getValue());
		
		personneService.addPersonne(personneMap, new AsyncCallback<Boolean>(){

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("failure");
				
			}

			@Override
			public void onSuccess(Boolean result) {
				ui.addHistoryItem("login");
				
			}
			
		});
	}

	@Override
	public Widget getWidget() {
		// TODO Auto-generated method stub
		return grid;
	}
}
